package models

import (
	"chat/utils"
	"gorm.io/gorm"
)

type Message struct {
	gorm.Model
	FromId   uint   `json:"fromId"`   // 发送者id，JSON字段为fromId（驼峰）
	TargetId uint   `json:"targetId"` // 接收者id，JSON字段为targetId（驼峰）
	Content  string `json:"content"`  // 内容，JSON字段为content（本身需一致）
}

func (table *Message) TableName() string {
	return "message"
}

func SendMessage(message Message) Message {
	utils.DB.Create(&message)
	return message
}

func GetMessageList(fromId uint, targetId uint) []Message {
	var messageList []Message
	utils.DB.Where("from_id = ? and target_id = ?", fromId, targetId).Or("from_id = ? and target_id = ?", targetId, fromId).Find(&messageList)
	return messageList
}

type MessageVo struct {
	Id       uint   `json:"id"`
	FromId   uint   `json:"fromId"`
	TargetId uint   `json:"targetId"`
	Content  string `json:"content"`
}

func MessageListToVo(messageList []Message) []MessageVo {
	messageVoList := make([]MessageVo, len(messageList))
	for i, message := range messageList {
		messageVoList[i] = MessageVo{
			Id:       message.ID,
			FromId:   message.FromId,
			TargetId: message.TargetId,
			Content:  message.Content,
		}
	}
	return messageVoList
}
